//
//  PublicNoticeView.m
//  SP2P
//
//  Created by Eternal on 2017/7/10.
//  Copyright © 2017年 EIMS. All rights reserved.
//

#import "PublicNoticeView.h"
#import "FilterHTML.h"
#import "MessageModel.h"
#import "AppDefaultUtil.h"
#import "NetWorkClient.h"
#import "MessageDetailViewController.h"
@interface PublicNoticeView ()<HTTPClientDelegate>

@property (weak, nonatomic) IBOutlet UILabel *publicLable;
@property (nonatomic ,strong) NetWorkClient *requestClient;
@property (nonatomic , assign) NSInteger currPage;
@property (nonatomic ,strong) NSMutableArray * dataArray;
@property (weak, nonatomic) IBOutlet UIImageView *publicImage;
@property (weak, nonatomic) IBOutlet UILabel *titleLable;
@property (weak, nonatomic) IBOutlet UILabel *lineLable;
@property (assign, nonatomic) BOOL isLoading;
@end
@implementation PublicNoticeView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self = [[[NSBundle mainBundle]loadNibNamed:@"PublicNoticeView" owner:self options:nil]lastObject];
        _currPage = 1;
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(publicClick)]];
        [self requestDataTitle];
    }
    return self;
}

- (void)publicClick{
    
    
    MessageModel *model = [_dataArray firstObject];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoMessage" object:model];
    
    
}
/**
 加载数据
 */
- (void)requestDataTitle{
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求,请稍后再试"];
        return;
    }
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"518" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:[NSString stringWithFormat:@"%ld",(long)_currPage] forKey:@"currPage"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
        
        
    }
     [_requestClient requestGet:@"app/services" withParameters:parameters];
   
 
}
// 返回成功
-(void) httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    _isLoading = NO;
    NSDictionary *dics = obj;
    DLOG(@"=交易记录返回成功=======%@",dics);
    
    if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-1"]) {
       
            // 清空全部数据
            if (_currPage == 1) {
                [_dataArray removeAllObjects];
            }
        
            NSArray *collections = [obj objectForKey:@"list"];
            for (NSDictionary *item in collections) {
                MessageModel *model = [MessageModel objectWithKeyValues:item];
                model.title = [item objectForKey:@"title"];
                model.messageId = [NSString stringWithFormat:@"%@",[item objectForKey:@"id"]];
                model.originContent = model.content;
                
                model.content = [FilterHTML filterHTML:model.content];
                model.content = [model.content stringByReplacingOccurrencesOfString:@"\t" withString:@""];
                model.content = [model.content stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                model.selectall = @"0";
                
                NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[[item objectForKey:@"time"] objectForKey:@"time"] doubleValue]/1000];
                NSDateFormatter *dataFormat = [[NSDateFormatter alloc] init];
                [dataFormat setDateFormat:@"yyyy-MM-dd"];
                model.timeStr = [self prettyDateWithReference:date];
                model.detailTimes = [dataFormat stringFromDate:date];
                [self.dataArray addObject:model];
            
            }
        self.publicLable.text = [[self.dataArray firstObject] title];
    }
    
    
}
-(void) startRequest {
    _isLoading = YES;
}
// 返回失败
-(void) httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    _isLoading = NO;
    // 服务器返回数据异常
    //    [SVProgressHUD showErrorWithStatus:@"网络异常"];
}

// 无可用的网络
-(void) networkError {
    _isLoading = NO;
    
    [SVProgressHUD showErrorWithStatus:@"无可用网络"];
}

// 数据
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataArray;
}
// 时间转换
- (NSString *)prettyDateWithReference:(NSDate *)reference {
    NSString *suffix = @"ago";
    
    float different = [reference timeIntervalSinceNow];
    if (different < 0) {
        different = -different;
        suffix = @"以前";
    }
    
    // days = different / (24 * 60 * 60), take the floor value
    float dayDifferent = floor(different / 86400);
    
    int days   = (int)dayDifferent;
    int weeks  = (int)ceil(dayDifferent / 7);
    int months = (int)ceil(dayDifferent / 30);
    int years  = (int)ceil(dayDifferent / 365);
    
    // It belongs to today
    if (dayDifferent <= 0) {
        // lower than 60 seconds
        if (different < 60) {
            return @"刚刚";
        }
        
        // lower than 120 seconds => one minute and lower than 60 seconds
        if (different < 120) {
            return [NSString stringWithFormat:@"1分钟 %@", suffix];
        }
        
        // lower than 60 minutes
        if (different < 660 * 60) {
            return [NSString stringWithFormat:@"%d分钟 %@", (int)floor(different / 60), suffix];
        }
        
        // lower than 60 * 2 minutes => one hour and lower than 60 minutes
        if (different < 7200) {
            return [NSString stringWithFormat:@"1小时%@", suffix];
        }
        
        // lower than one day
        if (different < 86400) {
            return [NSString stringWithFormat:@"%d小时%@", (int)floor(different / 3600), suffix];
        }
    }
    // lower than one week
    else if (days < 7) {
        return [NSString stringWithFormat:@"%d天%@%@", days, days == 1 ? @"" : @"", suffix];
    }
    // lager than one week but lower than a month
    else if (weeks < 4) {
        return [NSString stringWithFormat:@"%d天%@%@", weeks, weeks == 1 ? @"" : @"", suffix];
    }
    // lager than a month and lower than a year
    else if (months < 12) {
        return [NSString stringWithFormat:@"%d月%@%@", months, months == 1 ? @"" : @"", suffix];
    }
    // lager than a year
    else {
        return [NSString stringWithFormat:@"%d年%@%@", years, years == 1 ? @"" : @"", suffix];
    }
    
    return self.description;
}

@end
